package com.leosoft.heatmonitor.control;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.leosoft.heatmonitor.service.transactional.RoleService;
import com.leosoft.heatmonitor.service.transactional.UserService;

@Controller
@RequestMapping("/user")
public class UserController {

	@Autowired(required = true)
	UserService userService;
	@Autowired(required = true)
	RoleService roleService;

	String[] columns = { "id", "username", "nickname", "createtime", "role" };

	@RequestMapping(value = "/list")
	@ResponseBody
	public Map<String, Object> list(HttpServletRequest request) {
		int startIndex = Integer.parseInt(request.getParameter("start"));
		int length = Integer.parseInt(request.getParameter("length"));
		String draw = request.getParameter("draw");
		String searchValue = request.getParameter("search[value]");

		List<String[]> odrerPart = new ArrayList<>();
		List<String> wherePart = new ArrayList<>();

		for (int i = 0; i < columns.length; i++) {
			String orderColumn = request.getParameter("order[" + i
					+ "][column]");
			if (orderColumn != null) {
				String orderDir = request.getParameter("order[" + i + "][dir]");
				odrerPart.add(new String[] {
						columns[Integer.parseInt(orderColumn)], orderDir });
			}
			wherePart.add(columns[i]);
		}

		Map<String, Object> result = userService.list(startIndex, length,
				searchValue, wherePart, odrerPart);
		result.put("draw", draw);
		return result;
	}

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	ModelAndView create(@RequestParam("username") String username,
			@RequestParam("nickname") String nickname,
			@RequestParam("roleId") String roleId) {

		ModelAndView mv = new ModelAndView();
		mv.addObject("nav", "user");
		mv.setViewName("home");
		if (!userService.exsit(username)) {
			userService.create(username, nickname, roleId);
		} else {
			mv.addObject("error", "创建系统用户失败: 重复的系统用户!");
			return mv;
		}
		return mv;

	}

	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	String create(@RequestParam("id") String id) {
		userService.delete(id);
		return "redirect:/home/user";
	}

	@RequestMapping(value = "/update", method = RequestMethod.POST)
	String create(@RequestParam("id") String id,
			@RequestParam("username") String username,
			@RequestParam("nickname") String nickname,
			@RequestParam("roleId") String roleId) {

		userService.update(id, username, nickname, roleId);
		return "redirect:/home/user";
	}

	@RequestMapping(value = "/find/{id}")
	@ResponseBody
	public Map<String, Object> find(@PathVariable(value = "id") String id) {
		return userService.load(id);
	}

	@RequestMapping(value = "/changepassword")
	@ResponseBody
	String changePwd(@RequestParam("old") String old,
			@RequestParam("newp") String newp) {
		Object principal = SecurityContextHolder.getContext()
				.getAuthentication().getPrincipal();
		String username;
		if (principal instanceof UserDetails) {
			username = ((UserDetails) principal).getUsername();
		} else {
			username = principal.toString();
		}
		if (userService.check(username, old)) {
			userService.changePwd(username, newp);
			// daoAuthenticationProvider.getUserCache().removeUserFromCache(username);
			return "success";
		} else {
			return "error";
		}

	}

	@RequestMapping(value = "/getProject")
	@ResponseBody
	public List<Map<String, String>> getProject(@RequestParam("id") String id) {
		return userService.getProject(id);
	}

	@RequestMapping(value = "/control", method = RequestMethod.POST)
	String create(@RequestParam("userId") String userId,
			@RequestParam("projectId") String projectId) {
		String[] projectIds = projectId.split(",");
		userService.control(userId, projectIds);
		return "redirect:/home/user";
	}

	@RequestMapping(value = "/reset", method = RequestMethod.POST)
	String reset(@RequestParam("id") String id) {
		userService.reset(id);
		return "redirect:/home/user";
	}
}
